<?php

/**
* System 核心
*/

class System {
	
	static public $database = false;
	static public $config;
	
	public function __construct() {
		$this->init();
	}
	
	private function init() {
		$this->frontend();
		$this->controller();
	}
	
	private function controller() {
		include WEB_PATH . '/system/controller.class.php';
		new Controller();
	}
	
	static public function database() {
		if (self::$database) {
			return self::$database;
		}
		include WEB_PATH . '/system/database.class.php';
		$database = new Database();
		self::$database = $database->pdodb;
		return self::$database;
	}
	
	private function frontend() {
		$this->debugMode();
		$this->loadConfig();
		$this->loadGlobalFunction();
		$this->loadClass();
		$this->loadDefine();
	}

	private function debugMode() {
		$debug = defined('DEBUG') ? DEBUG : false;
		$debug = $debug == false ? 'Off' : 'On';
		error_reporting(E_ALL ^ E_NOTICE); // E_ALL ^ E_NOTICE ^ E_WARNING
		//error_reporting(E_ALL);
		ini_set("display_errors", $debug);
	}
	
	private function loadConfig() {
		$user_config_name = defined('USER_CFG') ? USER_CFG : 'user';
		$user_config = WEB_PATH . '/config/' . $user_config_name . '.cfg.php';
		$user = array();
		if (file_exists($user_config)) $user = include $user_config;
		$default = include WEB_PATH . '/system/core/config.php';
		$debug = array();
		$debug_path = WEB_PATH . '/config/debug.cfg.php';
		if (DEBUG && file_exists($bebug_path)) $debug = include $debug_path;
		self::$config = array_merge($default, $user, $debug);
	}
	
	private function loadGlobalFunction() {
		$conf = self::$config['System'];
		include WEB_PATH . '/system/core/function.php';
		foreach ($conf['funcs'] AS $func) {
			$func_path =  WEB_PATH . '/function/' . $func . '.fun.php';
			if (file_exists($func_path)) include $func_path;
		}
	}
	
	private function loadClass() {
		$conf = self::$config['System'];
		foreach ($conf['class'] AS $v) {
			$class_path =  WEB_PATH . '/include/' . $v . '.class.php';
			if (file_exists($class_path)) include $class_path;
		}

	}

	private function loadDefine() {
		include WEB_PATH . '/system/core/define.php';
	}
}